<?php

namespace app\aiapi\service;

use Symfony\Component\VarExporter\VarExporter;
use think\Exception;
/*
 * 微信V3支付服务层
 * */
class Wxpayv3
{
    //https://api.mch.weixin.qq.com/v3/pay/transactions/app
    /**
     * # +========================================================================
     * # | - @name        执行
     * # | - @author     cq <just_leaf@foxmail.com>
     * # | - @copyright zmtek 2021-01-20
     * # +========================================================================
     */
    public function execute($url,$body = null,$http_method = 'POST') {
        # 转化大写
        $http_method = strtoupper($http_method);
        if($http_method == 'POST') {

            $body   = json_encode($body);
        }else{

            $url    = $url . '?' . http_build_query($body);
            $body   = null;
        }
        # 分割符号
        $sign       = $this -> getV3Sign($url,$http_method,$body);
        $header[]   = 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36';
        $header[]   = 'Accept: application/json';
        $header[]   = 'Content-Type: application/json;';
        $header[]   = 'Authorization: WECHATPAY2-SHA256-RSA2048 '.$sign;

        $exc        = $this -> Curl($url,$body,$http_method,$header);
        return $exc;
    }


    /**
     * # +========================================================================
     * # | - @name        请求
     * # | - @author     cq <just_leaf@foxmail.com>
     * # | - @copyright zmtek 2021-01-20
     * # +========================================================================
     */
    public function Curl($url, $data, $http_method,$header = array(), $timeout = 30)
    {
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header,
            CURLOPT_URL            => $url,
            CURLOPT_HEADER         => 1 ,
        );

        # 根据请求类型设置特定参数
        if($http_method == 'POST') {

            # 判断是否传输文件
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $data;
        }

        # 初始化并执行curl请求
        $ch         = curl_init();
        curl_setopt_array($ch, $opts);

        $data       = curl_exec($ch);
        $error      = curl_error($ch);
        $httpCode   = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        list($headers, $body) = explode("\r\n\r\n", $data, 2);

        $result['data']     = $body;
        $result['httpcode'] = $httpCode;
        $result['headers']  = explode("\r\n", $headers);
        return  $result;
    }


    /**
     * # +========================================================================
     * # | - @name        签名
     * # | - @author     cq <just_leaf@foxmail.com>
     * # | - @copyright zmtek 2021-01-20
     * # +========================================================================
     */
    public function getV3Sign($url,$http_method,$body) {

        # 商户号
        $merchant_id    = "1604932491";
        # 随机字符串
        $nonce          = strtoupper($this -> getNoncestr());
        # 商户序列号
        $serial_no      = "4D910A1BF0F2E563E690C4F30F5042A3DE862008";
        # 时间搓
        $timestamp      = time();
        # url
        $url_parts      = parse_url($url);
        # 获取绝对路径
        $canonical_url  = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        # 密钥key
        $sslKeyPath = 'D:\phpstudy_pro\WWW\calculatefreight\public\apiclient_key.pem';
        //linux下更改
        $sslCertPath = "/www/wwwroot/cf.hy.meixinyun.net/public/apiclient_cert.pem";
        /* $sslKeyPath = "/www/wwwroot/cf.hy.meixinyun.net/public/apiclient_key.pem";*/
        //$private_key    = $this -> getPrivateKey($this -> SSLKEY_PATH);
        $private_key    = $this -> getPrivateKey($sslKeyPath);
        # 拼接参数
        $message        =
            $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";

        # 获取签名
        openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
        $sign   = base64_encode($raw_sign);

        $token  = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);
        return $token;
    }


    /**
     * # +========================================================================
     * # | - @name        获取私钥
     * # | - @author     cq <just_leaf@foxmail.com>
     * # | - @copyright zmtek 2019-12-26
     * # +========================================================================
     */
    public function getPrivateKey($filepath) {

        return openssl_get_privatekey(file_get_contents($filepath));
    }

    /**
     * # +========================================================================
     * # | - @name        获取随机数
     * # | - @author     cq <just_leaf@foxmail.com>
     * # | - @copyright zmtek 2021-01-20
     * # +========================================================================
     */
    public function getNoncestr($length = 32) {

        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
}